package netssl;

import javax.net.ssl.SSLServerSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class J_SSLServer {
    public static void main(String[] args){
        //指定密钥库和密码
        System.setProperty("javax.net.ssl.keyStore","F:\\temp\\new.keystore");
        System.setProperty("javax.net.ssl.keyStorePassword","123456");

        //获取服务器端套接字工厂的实例对象
        SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();

        try {
            ServerSocket ss = ssf.createServerSocket(5000);
            int i = 0;
            while (true){
                System.out.println("["+(++i)+"]:等待来自客户端的连接......");
                //监听并等待来自客户端的连接
                Socket s = ss.accept();
                PrintWriter pw = new PrintWriter(s.getOutputStream());
                InetAddress sa = s.getInetAddress();
                InetAddress ca = s.getLocalAddress();
                System.out.println("服务器端向客户端发送信息：");
                String str = "来自"+ca.getHostAddress()+"("+s.getLocalPort()+")"+"向"+sa.getHostAddress()+"("+s.getPort()+")发送的问候";
                System.out.println(str);
                pw.println(str);
                pw.flush();

                System.out.println("服务器端接收客户端信息：");
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                str = br.readLine();
                System.out.println(str);

                br.close();
                pw.close();
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
